package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.OrderItems;
import com.itljm.cxrMarket.entity.Orders;
import com.itljm.cxrMarket.entity.SysUser;
import com.itljm.cxrMarket.entity.dto.CreateOrderRequestDto;
import com.itljm.cxrMarket.entity.dto.OrderItemProductsDTO;
import com.itljm.cxrMarket.entity.dto.OrderStatusCountDTO;
import com.itljm.cxrMarket.service.OrdersService;
import com.itljm.cxrMarket.service.SysUserService;
import com.itljm.cxrMarket.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author ljm
 * @date 2024/12/28 11:52
 */
@RestController
@RequestMapping("/orders")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private SysUserService sysUserService;

    // 分页查询所有订单
    @RequestMapping("/info")
    public PageResult<Orders> selectAllOrderByPage(Integer page, Integer limit, String userName, String status,
                                                   String merchantId,String startOrderTime, String endOrderTime) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }
        Page<Orders> newPage = new Page<>(page, limit);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("1", 1);

        if (StringUtils.isNotEmpty(userName)) {
            SysUser user = sysUserService.selectIdByName(userName);
            if (null != user) {
                wrapper.eq("o.user_id", user.getId());
            }else {
                wrapper.eq("o.user_id", -1);
            }
        }
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("o.status", status);
        }
        if (merchantId != null && !merchantId.equals("1")) {
            wrapper.eq("p.product_id", merchantId);
        }
        if (StringUtils.isNotEmpty(startOrderTime) && StringUtils.isNotEmpty(endOrderTime)) {
            wrapper.ge("o.order_time", startOrderTime).le("o.order_time", endOrderTime);
        }

        List<Orders> orders = ordersService.selectAllOrdersPage(newPage, wrapper);
        return new PageResult<>(orders,newPage.getTotal());
    }

    // 根据id查询订单
    @RequestMapping("/info/{id}")
    public Result selectOrderById(@PathVariable Integer id) {
        Orders orders = ordersService.selectOrderById(id);
        return null != orders ? Result.ok(orders):Result.fail();
    }

    // 更新订单状态
    @RequestMapping("/update")
    public Result updateOrder(@RequestBody Orders order) {
        return ordersService.updateOrderStatus(order.getOrderId(),order.getStatus(),new Date()) ? Result.ok("更新成功"):Result.fail();
    }

    // 根据id删除订单
    @RequestMapping("/delete/{id}")
    public Result deleteOrder(@PathVariable Integer id) {
        return ordersService.deleteOrderById(id) ? Result.ok("删除成功"):Result.fail();
    }

    // 创建订单(小程序）
    @RequestMapping("/createOrder")
    public Result createOrder(@RequestBody CreateOrderRequestDto request) {
        Orders order = new Orders();
        order.setUserId(request.getUserId());
        order.setTotalAmount(request.getTotalAmount());
        order.setStatus(1);
        order.setPaymentMethod("内测零元购");
        order.setDeliveryAddress(request.getAddress());
        order.setOrderTime(new Date());

        List<OrderItems> orderItems = request.getOrderItems();

        String string = ordersService.insertOrder(order, orderItems);
        if ("111".equals(string)) {
            return Result.fail("库存不足，扣减失败");
        }
        if ("222".equals(string)) {
            return Result.fail("订单提交失败");
        }
        return Result.ok("提交成功");
    }

    // 根据订单id批量发货
    @RequestMapping("/batchDelivery")
    public Result batchDelivery(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            ordersService.updateOrderStatus(id, 2, new Date());
        }
        return Result.ok("批量发货成功");
    }

    // 根据id查询订单(小程序）
    @RequestMapping("/getOrderById")
    public Result getOrderById(Integer orderId) {
        Orders orders = ordersService.selectOrderById(orderId);
        return null != orders ? Result.ok(orders):Result.fail();
    }

    // 根据用户id查询订单/分页查询(小程序)
    @RequestMapping("/getOrdersByUserId")
    public PageResult<Orders> getOrdersByUserId(Integer page, Integer pageSize, Long userId, Integer status) {
        Page<Orders> newPage = new Page<>(page, pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("1", 1);

        if (status != null && status != 666) {
            wrapper.eq("status", status);
        }

        List<Orders> orders = ordersService.selectAllOrderByUserId(newPage,wrapper,userId);
        return new PageResult<>(orders,newPage.getTotal());
    }

    // 根据用户id查询订单(小程序)
    @RequestMapping("/getOrders")
    public PageResult<OrderItemProductsDTO> getOrders(Integer page, Integer pageSize, Long userId, Integer status) {
        Page<Orders> newPage = new Page<>(page, pageSize);
        if (status == null) {
            status = 0;
        }
        List<OrderItemProductsDTO> list = ordersService.selectOrders(newPage, status, userId);
        return new PageResult<>(list,newPage.getTotal());
    }

    // 查询各个状态的订单数量
    @RequestMapping("/count")
    public Result count(Long userId) {
        OrderStatusCountDTO orderStatusCountDTO = ordersService.countOrderStatusByUserId(userId);
        return Result.ok(orderStatusCountDTO);
    }

    // 取消订单
    @RequestMapping("/cancelOrder")
    public Result cancelOrder(Integer orderId) {
        return ordersService.updateOrderStatus(orderId, 0, new Date()) ? Result.ok("取消订单成功"):Result.fail();
    }

    // 确认收货
    @RequestMapping("/confirmReceipt")
    public Result confirmReceipt(Integer orderId) {
        return ordersService.updateOrderStatus(orderId, 4, new Date()) ? Result.ok("确认收货成功"):Result.fail();
    }

    // 根据用户是否购买过商品
    @RequestMapping("/isBuy")
    public Result isBuy(Long userId, Integer productId) {
        return ordersService.isBuy(userId,productId) ? Result.ok("已购买"):Result.fail();
    }
}
